package com.xianzhiOA.websocket;

import com.xianzhiOA.bean.XzEmp;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2017/5/9.
 */

@ServerEndpoint(value="/MsgSocket",configurator=HttpSessionConfigurator.class)
public class MsgSocket {
    private HttpSession httpSession;
    public static final Map<Long,Session> sessionMap = new HashMap<>();
    @OnMessage
    public void onMessage(String message, Session session) throws IOException, InterruptedException {
        XzEmp emp = (XzEmp) httpSession.getAttribute("userForeEnd");
        System.out.println("Received: " + message);

        Set<Session> sessionSet = session.getOpenSessions();
        for (Session session1 : sessionSet) {
            System.out.println("map中保存的session:"+session1.getId());
        }
        session.getBasicRemote().sendText("This is the last server message");
    }

    @OnError
    public void error(Session session, java.lang.Throwable throwable){
        System.err.println("Guest" + session.getId() + " error: " + throwable);
    }

    @OnOpen
    public void onOpen(Session session,EndpointConfig config) {
        httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        httpSession.setAttribute("mySocket",session);
        XzEmp emp = (XzEmp) httpSession.getAttribute("userForeEnd");
        if(emp!=null){
            sessionMap.put(emp.getEmpId(),session);
        }
        System.out.println(session.getId()+"Client connected");
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println(session.getId()+"Connection closed");
    }
}
